package org.com.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173", "http://localhost:5174", 
                              "http://localhost:5175", "http://localhost:5176",
                              "http://localhost:5177", "http://localhost:5178")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true); // 允许携带Cookie
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                String requestURI = request.getRequestURI();
                String method = request.getMethod();
                log.info("拦截到请求: {} {}", method, requestURI);
                
                // 放行支付宝相关接口
                if (requestURI.startsWith("/api/alipay/")) {
                    log.info("支付宝接口放行: {}", requestURI);
                    return true;
                }
                
                // 检查用户是否登录
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object userId = session.getAttribute("userId");
                    if (userId != null) {
                        log.info("用户已登录, userId: {}, 请求放行: {}", userId, requestURI);
                        return true;
                    } else {
                        log.warn("Session存在但userId为空, URI: {}", requestURI);
                    }
                } else {
                    log.warn("Session不存在, URI: {}", requestURI);
                }
                
                // 检查是否是排除的路径
                boolean isExcluded = requestURI.equals("/api/login") ||
                                   requestURI.equals("/api/logout") ||
                                   requestURI.equals("/api/addUser") ||
                                   requestURI.equals("/api/sendMsg") ||
                                   requestURI.equals("/api/findPassword") ||
                                   requestURI.equals("/api/products/list") ||
                                   requestURI.startsWith("/api/products/search") ||
                                   requestURI.startsWith("/api/products/category/") ||
                                   requestURI.startsWith("/api/products/detail/") ||
                                   requestURI.equals("/api/categories/list");
                
                if (isExcluded) {
                    log.info("公开接口放行: {}", requestURI);
                    return true;
                }
                
                log.warn("未授权访问被拦截: {}", requestURI);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }).addPathPatterns("/api/**");
    }
}